package com.nian.global.utils;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

/**
 * Created by nian on 2023/8/19.
 */
public class JsoupUtils {


    /**
     * Jsoup 的connection
     */
    public static Connection connection(JsoupArgs args) {

        Connection connect = Jsoup.connect(args.getUrl());

        // 设置代理
        if (!StringUtils.isEmpty(args.getHost()) && args.getPort() > 0) {
            connect = connect.proxy(args.getHost(), args.getPort());
        }
        // 设置超时时间
        if (args.getMillis() > 0) {
            connect = connect.timeout(args.getMillis());
        }
        //
        if (args.isIgnoreContentType()) {
            connect = connect.ignoreContentType(args.isIgnoreContentType());
        }
        //
        if (args.isIgnoreHttpErrors()) {
            connect = connect.ignoreHttpErrors(args.isIgnoreHttpErrors());
        }
        //
        if (args.getMaxBodySize() > 0) {
            connect = connect.maxBodySize(args.getMaxBodySize());
        }
        // 设置请求头
        if (args.getHeaders() != null && args.getHeaders().size() > 0) {
            connect = connect.headers(args.getHeaders());
        }
        // 设置cookies
        if (args.getCookies() != null && args.getCookies().size() > 0) {
            connect = connect.cookies(args.getCookies());
        }
        // 设置请求体
        if (!StringUtils.isEmpty(args.getBody())) {
            connect = connect.requestBody(args.getBody());
        }
        return connect;
    }

    /**
     * Jsoup 的get请求
     */
    public static Document get(JsoupArgs args) throws IOException {

        return connection(args).get();
    }

    /**
     * Jsoup 的post请求
     */
    public static Document post(JsoupArgs args) throws IOException {

        return connection(args).post();
    }

}
